<?php
/**
 * Created by PhpStorm.
 * User: glq
 * Date: 2018/11/23
 * Time: 9:16
 */
namespace Portal\Controller;

use Common\Controller\AdminbaseController;
use Portal\Model\PostsModel;
use Label\Model\CategoryModel;

// 快讯
class AdminNewsController extends AdminbaseController {

    protected $posts_model;
    protected $page_size;

    function _initialize() {
        parent::_initialize();
        $this->page_size    = 10;
        $this->posts_model  = D("Portal/Posts");
    }

    // 快讯列表
    public function news_list()
    {
        $this->_lists(array("post_status" => array('neq', 3), 'post_type' => PostsModel::POST_TYPE_NEWS));
        $this->display();
    }

    // 快讯添加
    public function add(){
        $post_categorys = M('category')->where(['type' => CategoryModel::CATEGORY_TYPE_NEWS, 'status' => 1])->order('id asc')->select();
        $this->assign('post_categorys', $post_categorys);
        $this->display();
    }

    // 快讯添加提交
    public function add_news(){
        if (IS_POST) {
            $category = $_POST['post']['category'];
            if (empty($category)) {
                $this->error("请至少选择一个分类！");
            }
            $_POST['post']['category'] = implode(',', $category);

            $labels = $_POST['post']['labels'];
            $labels = array_filter(explode(',', $labels));
            if (empty($labels)) {
                $this->error("请至少选择一个标签！");
            }
            $_POST['post']['labels'] = implode(',', $labels);

            $_POST['post']['post_modified'] = date("Y-m-d H:i:s",time());
            $_POST['post']['post_author']   = get_current_admin_id();
            $_POST['post']['post_type']     = PostsModel::POST_TYPE_NEWS;
            $_POST['smeta']['thumb']        = sp_asset_relative_url($_POST['smeta']['thumb']);

            $news=I("post.post");
            $news['post_content']=htmlspecialchars_decode($news['post_content']);
            $news['smeta'] = json_encode($_POST['smeta']);
            $result=$this->posts_model->add($news);
            if ($result) {
                $this->success("添加成功！");
            } else {
                $this->error("添加失败！");
            }
        }
    }


    // 问答编辑
    public function edit_news()
    {
        $id   = I('get.id', 0, 'intval');
        $post = $this->posts_model
            ->alias('p')
            ->where("id = $id")
            ->field('*, (select GROUP_CONCAT(name) FROM rx_label where FIND_IN_SET(id, p.labels) order by id) as label_names')
            ->find();
        if ($post && !empty($post['labels'])) {
            $post['label_names'] = array_filter(explode(',', $post['label_names']));
        } else {
            $post['label_names'] = [];
        }

        $post_categorys = M('category')->where(['type' => CategoryModel::CATEGORY_TYPE_NEWS, 'status' => 1])->order('id asc')->select();
        $this->assign('post_categorys', $post_categorys);

        $this->assign("smeta",json_decode($post['smeta'],true));
        $this->assign("post",$post);
        $this->display();
    }

    // 修改问答
    public function updateNews()
    {
        if (IS_POST) {

            $category = $_POST['post']['category'];
            if (empty($category)) {
                $this->error("请至少选择一个分类！");
            }
            $_POST['post']['category'] = implode(',', $category);

            $labels = $_POST['post']['labels'];
            $labels = array_filter(explode(',', $labels));
            if (empty($labels)) {
                $this->error("请至少选择一个标签！");
            }
            $_POST['post']['labels'] = implode(',', $labels);
            $_POST['post']['post_modified']= date("Y-m-d H:i:s",time());
            $_POST['smeta']['thumb'] = sp_asset_relative_url($_POST['smeta']['thumb']);

            $news = I("post.post");
            $news['post_content'] = htmlspecialchars_decode($news['post_content']);
            $news['smeta']=json_encode($_POST['smeta']);
            $result = $this->posts_model->save($news);
            if ($result !== false) {
                $this->success("保存成功！");
            } else {
                $this->error("保存失败！");
            }
        }
    }

    // 删除问答
    public function delNews()
    {
        $post_id = I('get.id', 0, 'intval');
        $this->posts_model->where(['id' => $post_id])->save(['post_status' => PostsModel::POST_STATUS_DEL]);
        $this->success('删除成功');
    }


    private function _lists($where = array()) {

        $start_time = I('request.start_time');
        if(!empty($start_time)){
            $where['p.post_date'] = array(
                array('EGT', $start_time)
            );
        }

        $end_time = I('request.end_time');
        if(!empty($end_time)){
            if(empty($where['p.post_date'])){
                $where['p.post_date'] = array();
            }
            array_push($where['p.post_date'], array('ELT', $end_time));
        }

        $keyword = I('request.keyword');
        if(!empty($keyword)){
            $where['p.post_title'] = array('like', "%$keyword%");
        }

        $author = I('request.author');
        if(!empty($author)){
            $where['c.user_nicename'] = array('like', "%$author%");
        }

        $count  = $this->posts_model->alias('p')->join("__USERS__ c ON p.post_author = c.id")->where($where)->count();
        $page   = $this->page($count, 20);

        $news = $this->posts_model
            ->alias("p")
            ->join("__USERS__ c ON p.post_author = c.id")
            ->where($where)
            ->limit($page->firstRow , $page->listRows)
            ->order("p.post_order desc, p.post_date DESC")
            ->field("p.*, c.user_nicename, c.user_login")
            ->select();

        foreach ($news as $k => $q) {
            if (empty($q['user_nicename'])) {
                $q['user_nicename'] = $q['user_login'];
                $news[$k] = $q;
            }
        }

        $this->assign("page", $page->show('Admin'));
        $this->assign("formget",array_merge($_GET, $_POST));
        $this->assign("news", $news);
    }

}